package com.jc.common.util;

import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.UUID;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CryptoUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(CryptoUtils.class);

	private CryptoUtils() {
		super();
	}

	/**
	 * <dl>
	 * <dt>说明：加密文本</dt>
	 * <dd>如果为空返回null</dd>
	 * </dl>
	 * @Title:encrypt
	 * @param content 需要加密的内容
	 * @param password 加密密码
	 * @return String
	 */
	public static String encrypt(String content, String password) {
		return content == null ? null : Base64.encodeBase64String(encryptByte(content, password));
	}

	/**
	 * <dl>
	 * <dt>说明：加密文本</dt>
	 * <dd>如果为空返回null</dd>
	 * </dl>
	 * @Title:encryptByte
	 * @param content 需要加密的内容
	 * @param password 加密密码
	 * @return byte[]
	 */
	public static byte[] encryptByte(String content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(password.getBytes());
			kgen.init(128, secureRandom);
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器 
			byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化 
			return cipher.doFinal(byteContent);// 加密 
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			LOGGER.error("{}-{}", content, e.getMessage(), e);
		} catch (IllegalBlockSizeException e) {
			LOGGER.error("内容未加密：{}-{}", content, e.getMessage());
		} catch (BadPaddingException e) {
			LOGGER.error("{}-{}", content, e.getMessage(), e);
		}
		return null;
	}

	/**
	 * <dl>
	 * <dt>说明：解密密文</dt>
	 * <dd>如果为空返回null</dd>
	 * </dl>
	 * @Title:decrypt
	 * @param content 需要加密的内容
	 * @param password 加密密码
	 * @return String
	 */
	public static String decrypt(String content, String password) {
		return content == null ? null : new String(decryptByte(Base64.decodeBase64(content), password));
	}

	//	private static Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
	//
	//	/**
	//	 * <dl>
	//	 * <dt>说明：解密密文</dt>
	//	 * <dd>如果为空返回null</dd>
	//	 * </dl>
	//	 * @Title:decrypt
	//	 * @param content 需要加密的内容
	//	 * @param password 加密密码
	//	 * @return String
	//	 */
	//	public static String decrypt(String content, String password) {
	//		try {
	//			if (content == null) {
	//				return null;
	//			} else {
	//				if (p.matcher(content).find()) { return content; }
	//				return new String(decryptByte(Base64.decodeBase64(content), password));
	//			}
	//		} catch (Exception e) {
	//			LOGGER.error("解密失败:{}-{}", content, e.getMessage());
	//			return content;
	//		}
	//	}

	/**
	 * <dl>
	 * <dt>说明：解密密文</dt>
	 * <dd>如果为空返回null</dd>
	 * </dl>
	 * @Title:decryptByte
	 * @param content 需要加密的内容
	 * @param password 加密密码
	 * @return byte[]
	 */
	public static byte[] decryptByte(byte[] content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
			secureRandom.setSeed(password.getBytes());
			kgen.init(128, secureRandom);
			//			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器 
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化 
			byte[] result = cipher.doFinal(content);
			return result; // 加密 
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			LOGGER.error("内容未加密：{}-{}", Base64.encodeBase64(content), e.getMessage());
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {

		String content = "18017978790";
		String sign = "fadfasdfadfll9dfe9a8df8asd8fad8f7asd7fad";
		System.out.println("加密前：" + content);
		String enstr = encrypt(content, sign);
		System.out.println("加密后:" + enstr);
		String destr = decrypt(enstr, sign);
		
		System.out.println("解密后:" + destr);
		
		//解密   
		//		byte[] decryptResult = decryptByte(encryptResult, password);
//		System.out.println("解密后：" + decrypt("b8dac96a-f3fe-46e9-8bef-0e1a9aeeb79f", "mgOSigXufOS7W5fHnm0z3j8IFFrdZUZ4lH3ovIGxkX0z3n+c+gfvaIvgjbRvVXrqOcXBeqJFhFeMlRxE1CzRAGnB7h6LAvGr98SjjbrEINY="));

//		System.out.println(decrypt("UeyjY05j96s1RetqKkkkaA==", "b8dac96a-f3fe-46e9-8bef-0e1a9aeeb79f"));

//		String secret = "3Y453454GDFGP353453453EUPRFG4534GFFG5345GF34";
//
//
//		String dec = "欢迎使用垃圾加密算法";
//
//
//		String MI = encrypt(dec,secret);
//		System.out.println(MI);
//		System.out.println(decrypt(MI, secret));

	}
}